/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s) {
  return binl2hex(core_md5(str2binl(s), s.length * chrsz));
}

function b64_md5(s) {
  return binl2b64(core_md5(str2binl(s), s.length * chrsz));
}

function str_md5(s) {
  return binl2str(core_md5(str2binl(s), s.length * chrsz));
}

function hex_hmac_md5(key, data) {
  return binl2hex(core_hmac_md5(key, data));
}

function b64_hmac_md5(key, data) {
  return binl2b64(core_hmac_md5(key, data));
}

function str_hmac_md5(key, data) {
  return binl2str(core_hmac_md5(key, data));
}

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test() {
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len) {
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a = 1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d = 271733878;

  for (var i = 0; i < x.length; i += 16) {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
    d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
    b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
    d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
    c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
    d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
    d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

    a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
    d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
    c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
    b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
    d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
    c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
    d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
    c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
    a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
    d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
    c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
    b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
    d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
    b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
    d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
    c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
    d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
    a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
    d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
    b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
    d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
    c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
    d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
    d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
    a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
    d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
    b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t) {
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}

function md5_ff(a, b, c, d, x, s, t) {
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}

function md5_gg(a, b, c, d, x, s, t) {
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}

function md5_hh(a, b, c, d, x, s, t) {
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}

function md5_ii(a, b, c, d, x, s, t) {
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data) {
  var bkey = str2binl(key);
  if (bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16),
    opad = Array(16);
  for (var i = 0; i < 16; i++) {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y) {
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt) {
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str) {
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for (var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin) {
  var str = "";
  var mask = (1 << chrsz) - 1;
  for (var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray) {
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for (var i = 0; i < binarray.length * 4; i++) {
    str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
      hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray) {
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for (var i = 0; i < binarray.length * 4; i += 3) {
    var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
    for (var j = 0; j < 4; j++) {
      if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
    }
  }
  return str;
}
// alert('in')
window.document.domain = "xunlei.com";
var active_cfg = window.active_cfg;
var cfg = {};
var month = [];
window.XLVIPPAYACT = function() {

  var orderid = '',
    po_active = 'normal',
    pay_url = 'http://dypay.vip.xunlei.com/actpay/activepay';
  cookies = [];

  //=======================================================================
  var show_msgbox = function(msghtml) {
    // 显示公共消息提示层
    // msghtml :消息内容，可以是string或者object，如果是object，则要有message属性。
    layoutCtrl.hide();
    var msg = msghtml;
    if (typeof msghtml == 'object') {
      msg = msghtml.message;
    }
    $('#alert_msg_p').html(msg);
    layoutCtrl.show('alert_msg_div', 'alert_msg_title');
  };

  // 渠道支付返回的错误消息
  // @param int code 错误码
  var pay_error_code = function(code) {
    code = parseInt(code);
    switch (code) {
      case 4:
        return '对不起，您的支付密码有误，请重新输入！';
      case 11:
        return '签名字符串不正确';
      case 12:
        return '订单号已存在';
      case 13:
        return '订单参数值不符合';
      case 14:
        return '无效商户号';
      case 15:
        return '账户余额不足';
      case 16:
        return '迅雷账户不存在';
      case 17:
        return '分润账户不在允许范围内';
      case 18:
        return '分润参数值不合法';
      case 20:
        return '错误的手机号码';
      case 21:
        return '不支持的手机号码段';
      case 22:
        return '手机号码存在VIP 包月';
      case 23:
        return '账户已经存在包月记录';
      case 26:
        return '请求失败，请更换手机或明天重新定制。';
      case 30:
        return '错误的电话号码';
      case 31:
        return '错误的声讯电话支付金额';
      case 32:
        return '发送齐顺声讯请求失败';
      case 33:
        return '发送联通固话请求失败';
      case 60:
        return '支付圈签约者支付宝帐号不正确';
      case 61:
        return '查询的支付圈签约者属于没签约的客户';
      case 62:
        return '支付圈签约者签约状态不正常';
      case 91:
        return '查询的支付成功订单不存在';
      case 92:
        return '迅雷账户是非充值用户';
      case 93:
        return '迅雷账户雷点信息查询内部错误';
      case 94:
        return '支付宝支付错误';
      case 95:
        return '雷点账户被冻结';
      case 96:
        return '雷点账户被关闭';
      case 98:
        return '银行卡未绑定';
      case 1001:
        return '支付密码错误';
      case 1002:
        return '超过最大支付限额';
      case 1003:
        return '支付网关请求异常';
      case 1004:
        return '该卡协议已过期，请重新<a href="http://pay.xunlei.com/yint_set1.html" target="_blank">绑定</a>';
      case 1005:
        return '订单异常';
      case 1006:
        return '帐号已经开通自动续费服务';
      default:
        return '未知错误';
    }
  };

  var layoutCtrl = {
    preid: '',
    show: function(divid, titleid) {
      this.hide(); //close first
      div_center(divid);
      $('#' + divid).fadeIn('show');
      if ($('#' + titleid).size() > 0) {
        mydraggable(titleid, divid);
      }
      this.preid = divid;
    },
    hide: function() {
      if (this.preid) $('#' + this.preid).css('display', 'none');
    }
  };

  var mydraggable = function(titleDivid, dragDivid) {
    document.getElementById(titleDivid).style.cursor = "move";
    document.getElementById(titleDivid).onmousedown = function(e) {
      var posX;
      var posY;
      var fdiv = document.getElementById(dragDivid);
      if (!e) e = window.event;
      posX = e.clientX - parseInt(fdiv.style.left);
      posY = e.clientY - parseInt(fdiv.style.top);
      document.onmousemove = function(ev) {
        if (ev == null) ev = window.event;
        fdiv.style.left = (ev.clientX - posX) + "px";
        fdiv.style.top = (ev.clientY - posY) + "px";
        return false;
      }
      document.onmouseup = function() {
        document.onmousemove = null;
      }
    }
  };

  var sumitform_iframe = function(formid) {
    if ($('#_submitIframe_').length < 1) {
      $(document.body).append('<iframe id="_submitIframe_" name="_submitIframe_" width="0" height="0" style="display:none;" />');
    }
    $('#' + formid).attr('target', '_submitIframe_');
    $('#' + formid).submit();
  };

  var div_center = function(div_id) {
    var divid = '#' + div_id;
    var divHeight = parseInt($(divid).height());
    var divWidth = parseInt($(divid).width());
    var divLeft = parseInt((document.documentElement.clientWidth - divWidth) / 2);
    var scrollTop = $(window).scrollTop();
    var clientHeight = $(window).height();
    var divTop = parseInt(((clientHeight - divHeight) / 2) + scrollTop);
    $(divid).css({
      position: 'fixed',
      top: divTop,
      left: divLeft,
      zIndex: 1002
    });
  };

  var get_cookie = function(name) {
    return (document.cookie.match(new RegExp("(^" + name + "| " + name + ")=([^;]*)")) == null) ? "" : decodeURIComponent(RegExp.$2);
  };

  var username = function() {
    var usernewno = get_cookie('usernewno');
    var usrname = get_cookie('usrname');
    if (usernewno && usernewno != '0') {
      return usernewno;
    }
    return usrname;
  };


  //=======================================================================

  //显示金额（不包含联名卡打折）
  var showmoney = function() {
    var month = parseInt($('[name=monthinfo]:checked').val());
    var origin = parseInt($('[name=monthinfo]:checked').attr('origin'));

    if (!month) {
      month = parseInt($('#othermonth').val());
      if (isNaN(month)) {
        $('#showmoney').text('0.0');
        return;
      }
    }

    var extdays = parseInt($('#po_extdays').val());

    if (isNaN(month)) {
      $('#showmoney').text('0.0');
      return;
    }

    var payway = $('[name=payway]:checked').val();
    if (payway == 'ld') {
      var unit = '雷点';
      $('.payunit').html(unit);
    } else {
      var unit = '元';
      $('.payunit').html(unit);
    }

    var prizetips = '';
    var money = '0.0';
    if (cfg['biztype'] == 'upgradevip' || cfg['biztype'] == 'upgradesuper' || cfg['biztype'] == 'knupsuperv1') {
      money = $('#nmUpdate').data('price');
    } else {
      money = cfg['price'][month]['price'];
    }

    //检测代金券
    if (money <= 0 || (global_paycenter['cash'] == 10 && month < 3 && global_paycenter['cash_unlimit'] != 1)) { // 无效，3个月及以上
      money = money;
      $('#po_cash').val('');
    } else {
      money = money - global_paycenter['cash'];
      $('#po_cash').val(global_paycenter['ticket']);
    }

    $('#po_extmoney').val('')
    $('#po_extdays').val('')
    $('#showmoney').text(money + unit);
    if (origin) {
      $('#origin').find('span').text(origin + unit).end().show();
    } else {
      $('#origin').hide();
    }
  };
  //代金券有关逻辑的函数;

  //检测代金券
  var cash_check = function() {
      $('#cash_list').hide();
      if ($.trim($('#cash_input').val()).length == 16) {
        var html = '<img src="http://img.vip.xunlei.com/img/loading.gif" align="absmiddle" /> 正在检测代金券...';
        $('#cash_status').html(html).show();
        var checkurl = 'http://dyact.vip.xunlei.com/cash/check_json/0/' + $.trim($('#cash_input').val()) + '?cachetime=' + new Date().getTime();
        $.ajax({
          type: "GET",
          url: checkurl,
          dataType: "jsonp",
          success: function(data) {

            //赋值代金券状态
            global_paycenter['cash_state'] = data.state;
            switch (data.state) {
              case 0:
                if (data.cash_minus == 10 && data.unlimit != 1) {
                  $('#cash_status').show().html('该代金券仅支付3个月会员及以上可用！再省' + data.cash_minus + '元</font>！');
                } else {
                  if (getMoney() < 0) {
                    $('#cash_status').show().html('该代金券仅下单金额大于' + data.cash_minus + '元可用！再省' + data.cash_minus + '元</font>！');
                  } else {
                    $('#cash_status').show().html('该代金券可用！再省' + data.cash_minus + '元</font>！');
                  }
                }
                global_paycenter['cash'] = data.cash_minus;
                global_paycenter['cash_unlimit'] = data.unlimit;
                refresh_vip_price();
                break;
              case 1:
                $('#cash_status').show().html('参数错误');
                global_paycenter['cash'] = 0;
                refresh_vip_price();
                break;
              case 2:
                $('#cash_status').show().html('代金券已过期');
                global_paycenter['cash'] = 0;
                refresh_vip_price();
                break;
              case 3:
                var min = parseInt(data.min) % 60;
                var hour = parseInt(parseInt(data.min) / 60);
                $('#cash_status').show().html('该代金券已被锁定，离解锁时间还剩' + hour + '小时' + min + '分钟');
                global_paycenter['cash'] = 0;
                refresh_vip_price();
                break;
              case 4:
                $('#cash_status').show().html('该代金券已经被使用');
                global_paycenter['cash'] = 0;
                refresh_vip_price();
                break;
              case 5:
                $('#cash_status').show().html('不存在该代金券');
                global_paycenter['cash'] = 0;
                refresh_vip_price();
                break;
              case 6:
                $('#cash_status').show().html('该代金券为其他用户的,您使用无效');
                global_paycenter['cash'] = 0;
                refresh_vip_price();
                break;
            }
          }
        });
      } else {
        global_paycenter['cash'] = 0;
        refresh_vip_price();
        global_paycenter['cash_state'] = -1;
        $('#cash_status').html('');
      }
      try {
        if ($('#cash_input').val().indexOf('代金券') === -1) {
          $('#po_cash').val($.trim($('#cash_input').val()));
        }
        cash_tips();
      } catch (e) {}
    },
    cash_check2 = function() {
      var cash_input = $('#cash_input').val();
      var length = $.trim($('#cash_input').val()).length;
      var imgbase = 'http://img.vip.xunlei.com/img/base/';
      var imgwow = '<img src="' + imgbase + 'wow16x16.png" align="absmiddle" />';
      //检测代金券长度
      if (length && length < 16 && cash_input.indexOf('代金券') === -1) {
        $('#cash_status').html('您输入的代金券位数不符').show();
      } else if (length == 0) {
        global_paycenter['cash'] = 0;
        global_paycenter['cash_state'] = -1;
        refresh_vip_price();
        $('#cash_status').html('');
        cash_tips();
      }
    },
    cash_tips = function() {
      var cash_val = $('#cash_input').val();
      if (cash_val == '' || cash_val.indexOf('代金券') !== -1) {
        var cash_tips = '';
        if (currentInfo.monthSelected >= 3) {
          cash_tips = '可用10元以下代金券';
        } else {
          cash_tips = '';
        }
        $('#cash_input').val(cash_tips);
        $('#cash_input').css({
          'font-size': '12px',
          'color': '#888888'
        });
      } else {
        $('#cash_input').css({
          'font-size': '14px',
          'color': '#000000'
        });
      }
    };


  //选择不同的支付方式
  var page_choose = function() {
    //选中高亮
    $('#div_payway,#div_month,#div_month2,#wcode_div').find('input[type=radio]').click(function() {
      $(this).parent().parent().find('span').removeClass('on');
      $(this).parent().addClass('on');
    });

    //显示金额
    $(document).on('click', '[name=monthinfo]', function() {
      $(this).closest('p').addClass('c_red').siblings('p').removeClass('c_red');
      showmoney();
    });

    //查询订单
    $(document).on('click', '#queryBtn', function() {
      var url = 'http://dypay.vip.xunlei.com/paycenter/chkorderid_easy?orderid=' + orderid + '&r=' + new Date().getTime();
      $.ajax({
        type: "GET",
        url: url,
        data: null,
        dataType: "jsonp",
        success: function(json) {
          if (json.result != 0) {
            alert(json.message);
            return false;
          }
          // 如果支付成功
          if (json.data.paysucc != '1') {
            // 支付不成功
            $('#querymsgtitle').hide().html('支付还未成功！').show(200);
            $('#query_ul_pay').hide();
            $('#query_ul_fail').show();
          } else {
            layoutCtrl.show('success_pop_id', 'success_pop_title');
          }
        }
      });
      return false;
    });

    //如果选中其他月数
    $(document).on('click', '#othermonth', function() {
      $('[name=monthinfo]:last').attr('checked', 'checked');
      $(this).parent().parent().find('span').removeClass('on');
      $(this).parent().addClass('on');
      if (!$(this).val()) {
        $(this).val('3')
      }
      showmoney();
    });

    //其他月数不能输入非数字
    $('#othermonth').keyup(function() {
      this.value = this.value.replace(/[^\d]/g, "");
      if (this.value.substring(0, 1) == '0') {
        this.value = '';
      }
      showmoney();
    });

    //选择其他月份，则输入月份清空
    $(document).on('click', '[name=monthinfo]', function() {
      if ($(this).val() == '0') {
        if ($('#othermonth').val() == '') {
          $('#othermonth').val('3');
          showmoney();
        }
      } else {
        $('#othermonth').val('');
      }
    });
    // 支付方式
    $('[name=paytype]').eq(0).click();

    //点支付按钮
    $(document).on('click', "#pay_btn", function() {
      // alert('in')
      $('#querymsgtitle').html('请您在新打开的页面完成支付！');
      $('#query_ul_pay').show();
      $('#query_ul_fail').hide();
      var po_month = parseInt($('[name=monthinfo]:checked').val());
      var payway = $('[name=payway]:checked').val();
      var paytype = $('[name=paytype]:checked').val();
      // 新增雷点密码支付
      if (payway == 'ld') {
        var password = $.trim($('#ld_pwd').val());
        $('#ld_pwd').val('');
        if (password.length <= 0) {
          $("#ld_pwd_tips").html('请填写支付密码！').show();
          $('#ld_pwd').focus();
          setTimeout(function() {
            $("#ld_pwd_tips").fadeOut();
          }, 3000);
          return false;
        } else if (password.length < 6 || password.length > 12) {
          $('#ld_pwd').focus();
          $("#ld_pwd_tips").html('您输入的支付密码位数不正确！').show();
          setTimeout(function() {
            $("#ld_pwd_tips").fadeOut();
          }, 3000);
          return false;
        }
        password = hex_md5(password);
        $('#po_ext2').val(password);
      }

      $('#po_ext1').val('');
      $('#po_month').val(po_month);
      $('#po_num').val(po_month);
      // $('#po_num2').val($('#po_taocan').val());
      $('#po_active').val(po_active);
      $('#po_source').val('');
      $('#po_way').val(payway);
      $('#myorderform').attr('target', '_blank').attr('action', pay_url);
      $('[name=qpuser]').text(username());
      if (payway == 'wy') {
        $('#po_source').val($('#pay_bank').val());
      }

      if (payway == 'ld') {
        $('#po_ext1').val('ld_callback');
        // 显示等待效果
        $(this).hide();
        $('#ld_wait_tips_div').show();
        // 提交到 iframe
        sumitform_iframe('myorderform');
      } else if (payway == 'wcode') {
        // alert('in') // 扫码支付
        //var paylink = pay_url + '?po_way='+payway+'&fgurl='+fgurl+'&po_active='+po_active+'&po_month='+po_month+'&po_num='+po_month+'&po_data='+encodeURIComponent($('#po_data').val())+'&po_ext1=wcode_callback&po_ext4=0&po_data2=wechatwebpay&referfrom='+referfrom+'&rt='+Math.random();
        if (paytype == 1) { // 微信
          payway = 'wcode';
          $('#loading-tip').show();
          $('#wcode_iframe').hide();
          $('#po_ext1').val('wcode_callback');
          $('#po_ext4').val('');
          $('#po_data2').val('wechatwebpay');
        } else {
          payway = 'alicode';
          $('#loading-tip').hide();
          $('#wcode_iframe').show();
          $('#po_ext1').val('');
          $('#po_ext4').val('0');
          $('#po_data2').val('');
        }
        $('#po_way').val(payway);
        var param = $("#myorderform").serialize();
        var paylink = pay_url + '?' + param;

        $('#wcode_iframe').html('<iframe name="iframe_wcode_name" id="iframe_wcode_name" src="' + paylink + '" scrolling="No"  width="646" height="300" frameborder="0"></iframe>');
        layoutCtrl.show('zfb_code_div', 'confirm_msg_title');
        //绑定关闭按钮
        $('#confirm_wcode_close').unbind().click(function() {
          layoutCtrl.hide();
          $(".flo_bg").hide();
          try {
            clearInterval(intervalId);
          } catch (e) {}
        });
      } else {
        $('#myorderform').submit();
        layoutCtrl.show('query_pop_id', 'query_pop_title');
      }

      return false;
    });

    //选择不同支付方式时
    $(document).on('click', '[name=payway]', function() {
      //隐藏银行
      $('.ext_block').hide();
      $('#ld_pwd_div').hide();
      if ($(this).val() == 'wy') {
        $('#bank_box').show();
      } else if ($(this).val() == 'ld') {
        $('#ld_pwd_div').show();
      } else if ($(this).val() == 'wcode') {
        $('#wcode_div').show();
      }
      showmoney();
    });

    $('[name=payway]').eq(0).click();
  };
  //代金券有关逻辑的函数;
  var global_paycenter = {
      'cash_state': -1,
      cash: 0
    }
    //检测代金券
  var cash_check = function() {
      $('#cash_list').hide();
      if ($.trim($('#cash_input').val()).length == 16) {
        var html = '<img src="http://img.vip.xunlei.com/img/loading.gif" align="absmiddle" /> 正在检测代金券...';
        var ticket = $.trim($('#cash_input').val());
        $('#cash_status').html(html).show();
        global_paycenter['ticket'] = ticket;
        var checkurl = 'http://dyact.vip.xunlei.com/cash/check_json/0/' + ticket + '?cachetime=' + new Date().getTime();
        $.ajax({
          type: "GET",
          url: checkurl,
          dataType: "jsonp",
          success: function(data) {

            //赋值代金券状态
            global_paycenter['cash_state'] = data.state;

            switch (data.state) {
              case 0:
                if (data.cash_minus == 10 && data.unlimit != 1) {
                  $('#cash_status').show().html('该代金券仅支付3个月会员及以上可用！再省' + data.cash_minus + '元</font>！');
                } else {

                  if (getMoney() < 0) {
                    $('#cash_status').show().html('该代金券仅下单金额大于' + data.cash_minus + '元可用！再省' + data.cash_minus + '元</font>！');
                  } else {
                    $('#cash_status').show().html('该代金券可用！再省' + data.cash_minus + '元</font>！');
                  }
                }
                global_paycenter['cash'] = data.cash_minus;
                global_paycenter['cash_unlimit'] = data.unlimit;
                showmoney();
                break;
              case 1:
                $('#cash_status').show().html('参数错误');
                global_paycenter['cash'] = 0;
                showmoney();
                break;
              case 2:
                $('#cash_status').show().html('代金券已过期');
                global_paycenter['cash'] = 0;
                showmoney();
                break;
              case 3:
                var min = parseInt(data.min) % 60;
                var hour = parseInt(parseInt(data.min) / 60);
                $('#cash_status').show().html('该代金券已被锁定，离解锁时间还剩' + hour + '小时' + min + '分钟');
                global_paycenter['cash'] = 0;
                showmoney();
                break;
              case 4:
                $('#cash_status').show().html('该代金券已经被使用');
                global_paycenter['cash'] = 0;
                showmoney();
                break;
              case 5:
                $('#cash_status').show().html('不存在该代金券');
                global_paycenter['cash'] = 0;
                showmoney();
                break;
              case 6:
                $('#cash_status').show().html('该代金券为其他用户的,您使用无效');
                global_paycenter['cash'] = 0;
                showmoney();
                break;
            }
          }
        });
      } else {
        global_paycenter['cash'] = 0;
        global_paycenter['ticket'] = '';
        showmoney();
        global_paycenter['cash_state'] = -1;
        $('#cash_status').html('');
      }
      try {
        if ($('#cash_input').val().indexOf('代金券') === -1) {
          $('#po_cash').val($.trim($('#cash_input').val()));
        }
        cash_tips();
      } catch (e) {}
    },
    cash_check2 = function() {
      var cash_input = $('#cash_input').val();
      var length = $.trim($('#cash_input').val()).length;
      var imgbase = 'http://img.vip.xunlei.com/img/base/';
      var imgwow = '<img src="' + imgbase + 'wow16x16.png" align="absmiddle" />';
      //检测代金券长度
      if (length && length < 16 && cash_input.indexOf('代金券') === -1 || length > 16) {
        $('#cash_status').html('您输入的代金券位数不符').show();
      } else if (length == 0) {
        global_paycenter['cash'] = 0;
        global_paycenter['cash_state'] = -1;
        showmoney();
        $('#cash_status').html('');
        cash_tips();
      } else {
        cash_check();
      }
    },
    cash_tips = function() {
      var cash_val = $('#cash_input').val();
      if (cash_val == '' || cash_val.indexOf('代金券') !== -1) {
        var cash_tips = '';
        if ($('input.monthchecked').val() >= 3) {
          cash_tips = '可用10元以下代金券';
        } else {
          cash_tips = '';
        }
        $('#cash_input').attr('placeholder', cash_tips);
        $('#cash_input').css({
          'font-size': '12px',
          'color': '#888888'
        });
      } else {
        $('#cash_input').css({
          'font-size': '14px',
          'color': '#000000'
        });
      }
    },
    getMoney = function() {
      return parseInt($('#showmoney').text());
    };

  function initCash() {
    getCashList();
    cash_check();
    $('#cash_item').show();
    $('i.ico_down').off('click').click(function() {
      $('#cash_list').toggle();
      return false;
    });
    $('#cash_list').on('click', 'a', function() {
      var item = $(this).data('item');
      $('#cash_input').val(item);
      cash_check();
    });
    $('#cash_input').on('keyup', function() {
      // alert('in');
      cash_check2();
    }).on('blur', function() {

      cash_check2();
    })
  }

  function getCashList() {
    var url = 'http://dyact.vip.xunlei.com/cash/cash_list' + "?_ts=" + (new Date()).getTime();
    ajax(url, function(rs) {
      $('#cash_list').html('');
      var ret = rs.ret;
      var cash_data = rs.data;
      if (ret == 0 && cash_data) {
        for (i in cash_data) {
          var prize = i / 100;
          var cash = cash_data[i]['fcard'];
          // var html = '<a item="'+cash+'" href="javascript:void(0);" onclick="return false" title="">'+prize+'元代金券</a>';
          var html = '<li><a data-item="' + cash + '"　href="javascript:void(0);" onclick="return false">' + prize + '元代金券</a></li>';
          $('#cash_list').append(html);
        }
        $('#cash_show').click();
        $('#cash_list li a').eq(0).click();
      } else {
        $('i.ico_down').hide();
      }
    });
  }

  return {
    save_orderid: function(oid) {
      orderid = oid;
    },
    ld_callback: function(json) {
      // json.data 0:成功(支付和开通服务都正常) 1：余额不足 2:支付失败 3：开通服务失败(此时已经支付成功了)
      var code = json.data;
      switch (code) {
        case 0:
          layoutCtrl.show('success_pop_id', 'success_pop_title');
          break;
        case 1:
          $('#ldrest').text(json.balance);
          layoutCtrl.show('ldfail_pop_id', 'ldfail_title');
          break;
        case 2:
          show_msgbox('服务器忙，请稍后再试！');
          break;
        case 3:
          show_msgbox('支付成功，系统将稍后为您开通服务！');
          break;
        default:
          var errmsg = pay_error_code(code);
          show_msgbox(errmsg);
          break;
      }
      $("#ld_wait_tips_div").hide();
      $("#pay_btn").show();
    },
    zfb_iframe_callback: function(rtn) {
      layoutCtrl.hide();
      if (rtn == '00') { // 如果支付成功
        layoutCtrl.show('success_pop_id', 'success_pop_title');
        $('[name=close_box]').one(function() {
          window.reloginfunc && window.reloginfunc();
        });
      } else { // 支付不成功
        $('#querymsgtitle').hide().html('尊敬的用户，您尚未完成支付！').show(200);
        $('#query_ul_pay').hide();
        $('#query_ul_fail').show();
      }
    },
    wcode_callback: function(json) {
      var code = json.data;
      var ext = json.ext;
      orderid = json.orderid;
      var cachetime = Math.random();
      $('#po_cachetime').val(cachetime);
      if (code == 3 && ext) {
        var codeHtml = '<img style="width:198px;height:198px;float:left;margin:50px 0 0 50px;" src="' + ext + '"></img><div style=" float:left;font-size: 18px;padding: 140px 0 0 60px;vertical-align: top;">请使用微信扫描二维码以完成支付</div>';
        $('#wcode_iframe').html(codeHtml);
        $('#loading-tip').hide();
        $('#wcode_iframe').show();
        intervalId = setInterval(function() {
          // 查询订单完成状态
          var url = 'http://dypay.vip.xunlei.com/paycenter/chkorderid_easy?orderid=' + orderid + '&r=' + new Date().getTime();
          $.ajax({
            type: "GET",
            url: url,
            data: null,
            dataType: "jsonp",
            success: function(json) {
              // 如果支付成功
              if (json.data.paysucc == '1') {
                layoutCtrl.show('success_pop_id', 'success_pop_title');
                $('[name=close_box]').one(function() {
                  window.reloginfunc && window.reloginfunc();
                });
                clearInterval(intervalId);
              }
            }
          });
        }, 2000);
      } else {
        show_msgbox('系统异常，请稍候重新下单。');
      }
    },
    init: function(reloginfunc, source, config) {
      po_active = source || 'vipopenday';
      page_choose();
      //绑定关闭按钮
      window.reloginfunc = reloginfunc;
      // $('[name=monthinfo]').eq(0).click();
      // $('[name=payway]').eq(0).click();
      $(document).on('click', '[name=close_box]', function() {
        layoutCtrl.hide();
        $('.layhi').hide();
        $(".flo_bg").hide();
      });

      //支付成功重新登录

      $(document).on('click', '[name=relogin_box]', function() {
        layoutCtrl.hide();
        reloginfunc(window.orderid);
        $(".flo_bg").hide();
        return false;
      });
    },
    open: function(actid, pid, config) {
      layoutCtrl.show('pay_box', 'pay_box_title');
      var isvip = getCookie('vip_isvip');
      var vas_type = getCookie('vas_type');
      var vip_paytype = getCookie('vip_paytype');
      var vip_isyear = getCookie('vip_isyear');
      var desc_html = '';
      var month_tips = '';
      $('#po_extdays').val(0);
      $('#po_extmoney').val(0);
      $('#div_month').show();
      $('#div_month2').hide();
      $('#po_actid').val(actid);
      $('#po_pid').val(pid);
      cfg = active_cfg['pay'][pid];

      window.aidfrom = cfg['aidfrom'] || '';
      $('#aidfrom').val(aidfrom);
      if (window.aidfrom != '') {
        $('#pay_btn').attr('clickid', window.aidfrom);
      }
      initPayWay(pid);
      var referfrom;
      if (active_cfg['pay'][pid]) {
        referfrom = getUrlParam(window.location.href, 'referfrom') || active_cfg['pay'][pid]['referfrom'] || getCookie('referfrom');
        // alert(referfrom)
      } else {
        referfrom = '';
      }
      $('#referfrom').val(referfrom);

      // 升级的逻辑

      if (cfg['biztype'] == 'upgradevip' || cfg['biztype'] == 'upgradesuper' || cfg['biztype'] == 'knupsuperv1') {
        var userid = getCookie('userid');
        var vastype = getCookie('vip_vastype');
        var biztype_config = {
          upgradevip: 3,
          upgradesuper: 5,
          knupsuperv1: 14
        }
        $('#cash_item').hide();
        $('#div_month_update').show();
        $('#div_month').hide();
        $('#content_tip').closest('p.sub_title').hide();
        $('#content_tip_update').closest('p.sub_title').show();
        var requestUrl = 'http://dypay.vip.xunlei.com/phonepay/getprice/?source=vipcenter&type=1&userid=' + userid + '&vastype=' + biztype_config[cfg['biztype']];
        ajax(requestUrl, function(rs) {
          //  返回说明：
          // ret      0 成功；1 无可升级订单;
          // prize    总价格
          // uprate   升级折扣
          // tdays    升级总天数
          // ndays    普通订单总天数
          // mtdays   迷你订单总天数
          //   nprize   普通订单价格
          // mprize   迷你订单价格
          // discount 优惠折扣 （原价 = prize / discount）
          // autopayprice 自动续费价格 （仅支付宝/微信白金包月返回）
          if (rs.ret == 0) {
            // $('#div_month_update').html('<span class="selpad02"></span>');
            if (rs.uprate == 1) {
              $('#div_month_update').html('<p class="c_red"><input type="radio" class="monthchecked" checked="" name="monthinfo" id="nmUpdate" origin="" value="' + rs.tdays + '" data-price="' + rs.price + '"><label for="nmUpdate">升级剩余时间<span>  <em style="color:#c80000;">' + rs.tdays + '</em> 天，需 <em style="color:#c80000;">' + rs.price + '</em> 元</span></label></p>');
            } else {
              $('#div_month_update').html('<p class="c_red"><input type="radio" class="monthchecked" checked="" name="monthinfo" id="nmUpdate" origin="" value="' + rs.tdays + '" data-price="' + rs.price + '"><label for="nmUpdate">升级剩余时间<span>  <em style="color:#c80000;">' + rs.tdays + '</em> 天，需 <em style="color:#c80000;">' + rs.price + '</em> 元，已打 <em style="color:#c80000;">' + rs.uprate * 10 + '</em> 折</span></label></p>');
            }

          } else {
            $('#div_month_update').html('<p class="c_red"><input type="radio" class="monthchecked" checked="" name="monthinfo" id="nmUpdate" origin="" value="' + rs.tdays + '" data-price="' + rs.price + '"><label for="nmUpdate">升级剩余时间<span>无升级时长</span></label></p>');
          }
          showmoney();
          $('#origin').hide();
          // $('#origin span').text(rs.nprice);


        })

      } else {
        month = [];
        if (cfg['usecash'] == 1) {
          initCash();
        } else {
          $('#cash_item').hide();
        }
        for (var i in cfg['price']) {
          cfg['price'][i]['month'] = i
          if (cfg['price'][i]['tips'] != '' && cfg['price'][i]['tips'].indexOf('(') == -1) {
            cfg['price'][i]['tips'] = ' ( ' + cfg['price'][i]['tips'] + ' )';
          }
          month.push(cfg['price'][i]);
        }
        var payunit = window.ACTCONFIG['payunit'] ? window.ACTCONFIG['payunit'] : "个月";
        var html = [];

        function sortNumber(a, b) {
          return b.month - a.month
        }
        if (active_cfg['pay'][pid]['pricedesc'] == 1) {
          month = month.sort(sortNumber)
        }
        var index_select = active_cfg['pay'][pid]['monthinfo'] || 0;
        for (var i = 0, len = month.length; i < len; i++) {
          if (i == index_select) {
            // alert('in')
            html.push('<p class="c_red"><input type="radio" class="monthchecked" checked name="monthinfo" id="nm' + month[i]['month'] + '" origin="' + month[i]['org_price'] + '"   value="' + month[i]['month'] + '"><label for="nm' + month[i]['month'] + '">' + (month[i]['other_name'] ? month[i]['other_name'] : month[i]['month'] + payunit) + '<span>' + month[i]['tips'] + '</span></label></p>')
          } else {
            html.push('<p class=""><input type="radio" name="monthinfo" id="nm' + month[i]['month'] + '" origin="' + month[i]['org_price'] + '" value="' + month[i]['month'] + '"><label for="nm' + month[i]['month'] + '">' + (month[i]['other_name'] ? month[i]['other_name'] : month[i]['month'] + payunit) + '<span>' + month[i]['tips'] + '</span></label></p>');
          }
        }
        $('#div_month').html(html.join(''));
        $('#div_month_update').hide();
        $('#div_month').show();
        $('#content_tip').closest('p.sub_title').show();
        $('#content_tip_update').closest('p.sub_title').hide();
      }

      if (cfg['tips'] && cfg['tips'].length) {
        $('#pay_tips').html(cfg['tips']);
      } else {
        $('#pay_tips').html('');
      }
      if (cfg['footertips'] && cfg['footertips'].length) {
        $('#footer_tips').html(cfg['footertips']);
      } else {
        $('#footer_tips').html('');
      }
      var inviteid = getUrlParam(location.href, 'uid');
      $('#po_inviteid').val(inviteid);
      // 来源统计点
      var referfrom = getUrlParam(location.href, 'referfrom');
      if (referfrom) {
        setCookie('vip_referfrom', referfrom);
      }
      $('a.monthchecked').click();
      $('[name=payway]:visible').eq(0).click();

      $('#pay_title,[name=qpmomth]').html(cfg['title']);
      $('#content_tip').html(window.ACTCONFIG['paytips']);
      if (commonvip()) {
        var desc_html = '';
        $('#pay_title').html('普通用户需先补齐差价，再开通白金才可获得抽奖机会');
        $('#content_tip').html('升级会员时长');
        var upgradeurl = 'http://dypay.vip.xunlei.com/user/upgradeinfo/?rt=' + Math.random();
        jsonCallBack(upgradeurl, function(rs) {
          var result = rs.result;
          var info = rs.data;
          var total_days = 0;
          if (result == 0) {
            var iscomplete = info.iscomplete;
            var days = info.days;
            if (days) {
              var day_item = days.split(':');
              var index = 0;
              var select_option = '';
              var option_all = '';
              for (i in day_item) {
                var day = parseInt(day_item[i]);
                if (day > 1) {
                  total_days += day;
                }
              }
            }
          }

          if (total_days > 0) {
            var month = (total_days / 31).toFixed(1);
            var curpay = month * 5;
            curpay = curpay.toFixed(1);
            var desc_html = '';
            var month_tips = '升级剩余时间' + total_days + '天 <strong>' + curpay + '<span class="payunit">元</span></strong>';
            $('#po_extmoney').val(curpay);
            $('#po_extdays').val(total_days);
          } else {
            var desc_html = '';
            var month_tips = '';
          }
          $('#div_month').hide();
          $('#div_month2').html(month_tips).show();
          $('#infotext1').html(desc_html);
          showmoney(curpay);
        });
      } else {
        $('#div_month2').html(month_tips);
        $('#infotext1').html(desc_html);
        // $('[name="monthinfo"]').each(function(){
        //   if ($(this).val() == taocan){
        //     $(this).click();
        //   }
        // });
        showmoney();
      }
    },
    set_payurl: function(url) {
      pay_url = url;
    },
    ld_back: function(json) {
      if (json) show_msgbox(json);
      // 恢复按钮
      $('#ld_wait_tips_div').hide();
      $('#ld_next_btn').show();
      $('#pay_btn').show();
    },
    //暴露所有内部方法，可以重新实现内部方法
    show_msgbox: show_msgbox,
    layoutCtrl: layoutCtrl,
    username: username,
    mydraggable: mydraggable,
    sumitform_iframe: sumitform_iframe,
    div_center: div_center,
    get_cookie: get_cookie
  };

}();

function initPayWay(pid) {
  var payway = active_cfg['pay'][pid]['payway'];
  payway = $.trim(payway);
  if (typeof payway == 'undefined' || typeof payway == 'null' || payway.length == 0) {

    $('#div_payway span.selpad').show();
    $('[data-payway=jd]').hide();

  } else {
    $('#div_payway span.selpad').each(function() {
      var subpayway = $(this).data('payway');
      if (payway.indexOf(subpayway) != -1) {
        // conso
        $(this).show();
      } else {
        $(this).hide();
      }
    })
  }

}


function ajax(url, callback, error) {
  var deffered = $.ajax({
    url: url,
    dataType: 'jsonp',
    type: 'GET',
    statusCode: {
      404: function() {
        error();
      }
    }
  }).done(function(data) {
    callback && callback(data);
  }).fail(function(err) {
    error && error(err);
  });
  return deffered;
};

function getUrlParam(url, key) {
  var reg = "/^.*[\\?|\\&]" + key + "\\=([^\\&]*)/";
  reg = eval(reg);
  var ret = url.match(reg);
  if (ret != null) {
    return decodeURIComponent(ret[1]);
  } else {
    return "";
  }
}

function commonvip() {
  return false;
}

var show_msgbox = function(msghtml) {
  XLVIPPAYACT.show_msgbox(msghtml);
};


window.save_orderid = XLVIPPAYACT.save_orderid;
window.ld_callback = XLVIPPAYACT.ld_callback;
window.zfb_iframe_callback = XLVIPPAYACT.zfb_iframe_callback;
window.ld_back = XLVIPPAYACT.ld_back;
var wcode_callback = XLVIPPAYACT.wcode_callback;
/*
 * 使用方法：
 *
 * 初始化
 * XLVIPPAYACT.init(function(){ 重新登录的函数 },'vod');
 *
 * 打开支付浮层
 * XLVIPPAYACT.open();
 */
window.XLVIPPAYACT = XLVIPPAYACT;